package com.iw.adoms.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.iw.adoms.utils.QrCodeUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iw.adoms.entity.Brand;
import com.iw.adoms.entity.Department;
import com.iw.adoms.entity.Goods;
import com.iw.adoms.entity.Marchandise;
import com.iw.adoms.entity.Order;
import com.iw.adoms.entity.QrBoxCode;
import com.iw.adoms.entity.QrGoodsCode;
import com.iw.adoms.entity.StorageBatch;
import com.iw.adoms.entity.neum.Status;
import com.iw.adoms.service.BrandService;
import com.iw.adoms.service.DepartmentService;
import com.iw.adoms.service.GoodsService;
import com.iw.adoms.service.MarchandiseService;
import com.iw.adoms.service.OrderService;
import com.iw.adoms.service.QrBoxCodeService;
import com.iw.adoms.service.QrGoodsCodeService;
import com.iw.adoms.service.StorageBatchService;
import com.iw.adoms.vo.ScanGoodsVO;
import com.iw.core.orm.Filtration;
import com.iw.core.orm.Filtration.MatchType;
import com.iw.core.orm.PageData;
import com.iw.core.utils.WebUtils;

@Controller
@RequestMapping("/adoms/goods")
public class GoodsAction extends BaseAction {
	private static final Logger LOGGER = Logger.getLogger(GoodsAction.class);
	@Resource
	private GoodsService goodsService;
	@Resource
	private MarchandiseService marchandiseService;
	@Resource
	private QrGoodsCodeService qrGoodsCodeService;
	@Resource
	private OrderService orderService;
	@Resource
	private BrandService brandService;
	@Resource
	private QrBoxCodeService qrBoxCodeService;
	@Resource
	private StorageBatchService storageBatchService;
	@Resource
	private DepartmentService departmentService;

	@RequestMapping("/list")
	public ModelMap list(HttpServletRequest request) {
		PageData<Goods> pageData = new PageData<Goods>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		pageData = goodsService.find(pageData);

		return new ModelMap(pageData);
	}

	@RequestMapping("/statistics")
	public ModelMap statistics(HttpServletRequest request) {
		PageData<Goods> pageData = new PageData<Goods>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);

		Integer dId = getCurrentUser(request).getDepartment().getId();
		Filtration filter = new Filtration(MatchType.EQ, dId, "department.id");
		pageData.addFiltrations(filter);

		pageData = goodsService.find(pageData);

		return new ModelMap(pageData);
	}

	@RequestMapping("/myList")
	public ModelMap myList(HttpServletRequest request) {
		PageData<Goods> pageData = new PageData<Goods>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);

		Integer dId = getCurrentUser(request).getDepartment().getId();
		Filtration filter = new Filtration(MatchType.EQ, dId, "department.id");
		pageData.addFiltrations(filter);

		pageData = goodsService.find(pageData);

		return new ModelMap(pageData);
	}

	@RequestMapping("/orderGoods")
	public ModelMap viewByOrder(HttpServletRequest request, Integer orderId) {
		PageData<Goods> pageData = new PageData<Goods>();
		Order order = orderService.find(orderId);
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		Filtration filter = new Filtration(MatchType.EQ, orderId, "order.id");
		pageData.getFiltrations().add(filter);
		pageData.getPagination().setPageSize(10000);
		pageData = goodsService.find(pageData);

		return new ModelMap(pageData).addAttribute(order);
	}

	@RequestMapping(value = "/storage", method = RequestMethod.GET)
	public String storage(Model model, HttpServletRequest request) {
		commonIn(model, request);
		return "/adoms/goods/storage";
	}

	@RequestMapping(value = "/storage", method = RequestMethod.POST)
	@ResponseBody
	public boolean storage(StorageBatch storageBatch, Model model, Goods goods, Integer boxid[], Integer qrid[]) {
		try {
			if (qrid != null) {
				storageBatch.setNumOfMarchandise(qrid.length); // 总的商品数量
				storageBatchService.save(storageBatch);

				// 新增货物
				for (Integer qid : qrid) {
					QrGoodsCode goodQr = qrGoodsCodeService.find(qid);
					goods.setQrCode(goodQr);
					goods.setId(null);
					goods.setState(Status.WILL_SALE.getValue());
					goods.setProduceDate(storageBatch.getProduceDate());
					goodsService.save(goods);
					// 更新货物二维码表中的状态
					goodQr.setState(Status.HAS_IN.getValue());
					qrGoodsCodeService.update(goodQr);
				}

				// 更新箱码的状态
				if (boxid != null) {
					for (Integer bid : boxid) {
						QrBoxCode box = qrBoxCodeService.find(bid);
						box.setState(Status.HAS_IN.getValue());
						qrBoxCodeService.update(box);
					}
				}

				return true;
			}
		} catch (Exception e) {
			LOGGER.error("GoodsAction:" + e.getMessage());
		}
		return false;
	}

	@RequestMapping(value = "/inStock", method = RequestMethod.GET)
	public String inStock(Model model, HttpServletRequest request) {
		commonIn(model, request);
		return "/adoms/goods/inStock";
	}

	@RequestMapping(value = "/inStock", method = RequestMethod.POST)
	public String inStock(Model model, Goods goods, HttpServletRequest request) {
		try {
			goods.setState(Status.WILL_SALE.getValue());
			goodsService.save(goods);
			// 更新货物二维码表中的状态
			QrGoodsCode goodQr = qrGoodsCodeService.find(goods.getQrCode().getId());
			goodQr.setState(Status.WILL_SALE.getValue());
			qrGoodsCodeService.update(goodQr);
			model.addAttribute("msg", "入库操作成功！");
		} catch (Exception e) {
			model.addAttribute("msg", "操作失败，请重试！");
			LOGGER.error("GoodsAction:" + e.getMessage());
		}
		commonIn(model, request);
		return "/adoms/goods/inStock";
	}

	private void commonIn(Model model, HttpServletRequest request) {

		List<Marchandise> mList = new ArrayList<Marchandise>();
		List<Marchandise> mAll = marchandiseService.findAll();
		Integer did = getCurrentUser(request).getDepartment().getId();
		List<Brand> allBrand = brandService.findAll();
		Set<Brand> myBrands = new HashSet<Brand>();
		for (Brand b : allBrand) {
			Set<Department> departs = b.getDepartment();
			for (Department d : departs) {
				if (d.getId().equals(did)) {
					myBrands.add(b);
				}
			}
		}
		// 只取代理的品牌下面的代理商品
		for (Marchandise m : mAll) {
			for (Brand b : myBrands) {
				if (b.getId().equals(m.getBrand().getId())) {
					if (!mList.contains(m)) {
						mList.add(m);
					}
				}
			}
		}

		model.addAttribute("mList", mList);

	}

	@RequestMapping(value = "/batchIn", method = RequestMethod.GET)
	public String batchIn(Model model, HttpServletRequest request) {
		commonIn(model, request);
		return "/adoms/goods/batchIn";
	}

	@RequestMapping(value = "/batchIn", method = RequestMethod.POST)
	public String batchIn(Goods goods, Model model, Integer qrid[], HttpServletRequest request) {
		try {
			for (Integer qid : qrid) {
				QrGoodsCode goodQr = qrGoodsCodeService.find(qid);
				goods.setQrCode(goodQr);
				goods.setId(null);
				goods.setState(Status.WILL_SALE.getValue());
				goodsService.save(goods);
				// 更新货物二维码表中的状态
				goodQr.setState(Status.WILL_SALE.getValue());
				qrGoodsCodeService.update(goodQr);
			}
			model.addAttribute("msg", "批量入库操作成功！");
		} catch (Exception e) {
			model.addAttribute("msg", "操作失败，请重试！");
			LOGGER.error("GoodsAction:" + e.getMessage());
		}
		commonIn(model, request);
		return "/adoms/goods/batchIn";
	}

	private void outStockCommon(Model model, HttpServletRequest request) {
		Integer mDid = getCurrentUser(request).getDepartment().getId();
		// List<Order> orderList = orderService.findList("from Order where ((departmentTarget.id=? and type=? )) and status=?", mDid, true, Status.ORDER_WILL_SHIP);
		List<Order> orderList = orderService.findList("from Order where ((departmentTarget.id=? and type=? and status=?) or (department.id=? and type=? and status=?)) ", mDid, true,Status.ORDER_WILL_SHIP, mDid, false,
				Status.ON_RETURN);
		model.addAttribute("orderList", orderList);
	}

	@RequestMapping(value = "/outStock", method = RequestMethod.GET)
	public String outStock(Model model, HttpServletRequest request) {
		outStockCommon(model, request);
		return "/adoms/goods/outStock";
	}

	@RequestMapping(value = "/outStock", method = RequestMethod.POST)
	public String outStock(Order order, Integer[] goodsId, HttpServletRequest request, Model model) {
		try {
			goodsService.outStock(order, goodsId, request);
			model.addAttribute("msg", "出库操作成功！");
		} catch (Exception e) {
			model.addAttribute("msg", "出库操作异常！");
			e.printStackTrace();
		}
		outStockCommon(model, request);
		return "/adoms/goods/outStock";
	}

	@RequestMapping(value = "/new")
	public String addForm(Model model) {
		return "/adoms/goods/input";
	}

	@RequestMapping(value = "/edit/{id}")
	public String editForm(@PathVariable("id") Integer id, Model model) {
		Goods goods = goodsService.find(id);
		model.addAttribute(goods);
		List<Marchandise> mList = marchandiseService.findAll();
		model.addAttribute("mList", mList);
		return "/adoms/goods/input";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Goods goods) {
		try {
			if (goods.isNew()) {
				goodsService.save(goods);
				// 更新货物二维码表中的状态
				QrGoodsCode goodQr = qrGoodsCodeService.find(goods.getQrCode().getId());
				goodQr.setState(Status.WILL_SALE.getValue());
				qrGoodsCodeService.update(goodQr);
			} else {
				goodsService.update(goods);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/adoms/goods/list";// 重定向
	}

	@RequestMapping(value = "/myStock")
	public String myStock(Model model, HttpServletRequest request, Integer mid) {

		Integer departmentId = this.getCurrentDepartmentId(request);
		marchandiseService.myStock(model, departmentId, mid);
		return "/adoms/goods/myStock";
	}

	@RequestMapping(value = "/departmentStock")
	public String departmentStock(Model model, HttpServletRequest request, Integer mid, Integer did) {
		Integer departmentId = this.getCurrentDepartmentId(request);
		String hql = "from Department where department.id = ? and 1=?";
		List<Department> dlist = departmentService.findList(hql, departmentId, 1);
		if (dlist.size() > 0) {
			if (did == null || did == 0) {
				did = dlist.get(0).getId();
			}
			marchandiseService.myStock(model, did, mid);
			model.addAttribute("did", did);
			model.addAttribute("dlist", dlist);
		}
		return "/adoms/goods/departmentStock";
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") Integer id) {
		goodsService.delete(id);
		return "redirect:/adoms/goods/list";// 重定向
	}

	@RequestMapping(value = "/visible/{id}")
	public String visible(@PathVariable("id") Integer id) {
		goodsService.visible(id);
		return "redirect:/adoms/goods/list";// 重定向
	}

	@RequestMapping(value = "/unVisible/{id}")
	public String unVisible(@PathVariable("id") Integer id) {
		goodsService.unVisible(id);
		return "redirect:/adoms/goods/list";// 重定向
	}

	@RequestMapping(value = "/stockDetail/{mid}")
	public String stockDetail(Model model, HttpServletRequest request, @PathVariable("mid") Integer mid) {
		Integer departmentId = this.getCurrentDepartmentId(request);
		marchandiseService.stockDetail(model, departmentId, mid);
		return "/adoms/goods/stockDetail";
	}

	@RequestMapping(value = "/goodsDetail")
	public String goodsDetailByQr(Model model, HttpServletRequest request, String qr) {
		qr = qr.trim().replace(" ", "");
		Integer departmentId = this.getCurrentDepartmentId(request);
		String hql = "from Goods where qrCode.qrCode = ? and department.id = ? and state = ?";
		List<Goods> list = goodsService.findList(hql, qr, departmentId, Status.WILL_SALE.getValue());
		if (!list.isEmpty()) {
			model.addAttribute("goods", list.get(0));
		} else {
			hql = "from QrBoxCode where qrCode = ? and 1 = ?";
			List<QrBoxCode> boxList = qrBoxCodeService.findList(hql, qr, 1);
			if (!boxList.isEmpty()) {
				model.addAttribute("box", boxList.get(0));
			}
		}
		return "/adoms/goods/goodsDetail";
	}

	@RequestMapping(value = "/getGoodsByCode")
	public @ResponseBody
	Goods getGoodsByCode(String qrCode, HttpServletRequest request) {
		qrCode = qrCode.trim().replace(" ", "");
		Filtration filter = new Filtration(MatchType.EQ, qrCode, "qrCode.qrCode");
		Filtration fStatus = new Filtration(MatchType.EQ, Status.WILL_SALE.getValue(), "state");
		Filtration fDepartment = new Filtration(MatchType.EQ, getCurrentUser(request).getDepartment().getId(), "department.id");
		List<Goods> goods = goodsService.findList(filter, fStatus, fDepartment);
		Goods g = null;
		if (goods.size() > 0) {
			g = goods.get(0);
			g.setMemo(g.getMarchandise().getName());
			g.setSalesState(String.valueOf(g.getMarchandise().getId()));
		}
		return g;
	}

	/**
	 * 按二维码来扫描要出库的本部门的GOODS
	 * 
	 * @param qrCode
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getGoodsByCodeOrBox")
	public @ResponseBody
	List<ScanGoodsVO> getGoodsByCodeOrBox(String qrCode, HttpServletRequest request) {

		qrCode = qrCode.trim().replace(" ", "");
        //2013.10.10
        String wCode = QrCodeUtil.getCode(qrCode);

		List<ScanGoodsVO> scanGoodsVOs = null;
		Integer dpId = this.getCurrentDepartmentId(request); // 取得当前部门ID

		// qr code 为箱码
		String hql = "from Goods where qrCode.box.wCode = ? and department.id = ? and state = ?";
		List<Goods> listGoods = goodsService.findList(hql, wCode, dpId, Status.WILL_SALE.getValue());
		if (listGoods == null || listGoods.size() < 1) {
			// qr code 为普通的二维码
			hql = "from Goods where qrCode.wCode = ? and department.id = ? and state = ?";
			listGoods = goodsService.findList(hql, wCode, dpId, Status.WILL_SALE.getValue());
			// 一个二维码保证只有一个
			if (listGoods != null && listGoods.size() > 0) {
				Goods g = listGoods.get(0);
				listGoods.clear();
				listGoods.add(g);
			}
		}
		if (listGoods != null) {
			scanGoodsVOs = new ArrayList<ScanGoodsVO>();
			for (Goods goods : listGoods) {
				ScanGoodsVO vo = new ScanGoodsVO(goods);
				scanGoodsVOs.add(vo);
			}
		}

		return scanGoodsVOs;
	}

}
